import { Request, Response } from 'express';
import { spawn } from 'child_process';
import path from 'path';
import fs from 'fs';
import mysql from 'mysql2/promise';
import { RowDataPacket } from 'mysql2';

interface VideoSettings {
  style: string;
  speed: number;
  backgroundMusic: boolean;
  quality: 'high' | 'medium' | 'low';
  resolution: '1080p' | '720p' | '480p';
}

interface VideoProgress {
  progress: number;
  status: 'processing' | 'completed' | 'failed';
  message?: string;
  timestamp: number;
}

interface VideoRow extends RowDataPacket {
  id: number;
  video_id: string;
  ppt_path: string;
  output_path: string;
  status: string;
  created_at: Date;
  updated_at: Date;
}

// 视频生成配置
const VIDEO_CONFIGS = {
  '1080p': { width: 1920, height: 1080 },
  '720p': { width: 1280, height: 720 },
  '480p': { width: 854, height: 480 }
};

// 质量配置
const QUALITY_CONFIGS = {
  'high': { crf: '18', preset: 'slow' },
  'medium': { crf: '23', preset: 'medium' },
  'low': { crf: '28', preset: 'fast' }
};

// 存储视频生成进度
const videoProgress = new Map<string, VideoProgress>();

// 清理过期进度信息
const cleanupProgress = () => {
  const now = Date.now();
  for (const [key, value] of videoProgress.entries()) {
    if (now - value.timestamp > 24 * 60 * 60 * 1000) { // 24小时后清理
      videoProgress.delete(key);
    }
  }
};

setInterval(cleanupProgress, 60 * 60 * 1000); // 每小时清理一次

// 重试机制
const retry = async <T>(
  operation: () => Promise<T>,
  maxRetries: number = 3,
  delay: number = 1000
): Promise<T> => {
  let lastError: Error;
  
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await operation();
    } catch (error) {
      lastError = error as Error;
      if (i < maxRetries - 1) {
        await new Promise(resolve => setTimeout(resolve, delay * (i + 1)));
        continue;
      }
    }
  }
  
  throw lastError!;
};

// 数据库配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'DHY963dlm',
  database: 'aiteach'
};

// 创建数据库连接池
const pool = mysql.createPool(dbConfig);

// 生成视频
export const generateVideo = async (req: Request, res: Response) => {
  try {
    const { fileUrl, settings } = req.body;
    
    if (!fileUrl) {
      return res.status(400).json({
        success: false,
        message: '请提供文件URL'
      });
    }

    // 生成唯一的视频ID
    const videoId = Date.now().toString();
    const outputPath = path.join(process.cwd(), 'output', `${videoId}.mp4`);

    // 确保输出目录存在
    const outputDir = path.dirname(outputPath);
    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir, { recursive: true });
    }

    // 从URL中获取文件路径
    const filePath = path.join(process.cwd(), fileUrl.replace(/^\/uploads\//, 'uploads/'));
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        success: false,
        message: '文件不存在'
      });
    }

    // 保存视频记录到数据库
    const connection = await pool.getConnection();
    try {
      await connection.execute(
        'INSERT INTO videos (video_id, ppt_path, input_path, output_path, status) VALUES (?, ?, ?, ?, ?)',
        [videoId, filePath, filePath, outputPath, 'processing']
      );
    } finally {
      connection.release();
    }

    // 启动视频生成进程
    const pythonScript = path.join(process.cwd(), 'scripts', 'generate_video.py');
    const pythonProcess = spawn('python', [pythonScript, filePath, outputPath], {
      env: {
        ...process.env
      }
    });

    let errorOutput = '';

    pythonProcess.stderr.on('data', (data) => {
      errorOutput += data.toString();
      console.error('Python错误:', data.toString());
    });

    pythonProcess.stdout.on('data', (data) => {
      console.log('Python输出:', data.toString());
    });

    pythonProcess.on('close', async (code) => {
      const connection = await pool.getConnection();
      try {
        if (code === 0) {
          await connection.execute(
            'UPDATE videos SET status = ? WHERE video_id = ?',
            ['completed', videoId]
          );
        } else {
          await connection.execute(
            'UPDATE videos SET status = ?, error_message = ? WHERE video_id = ?',
            ['failed', errorOutput, videoId]
          );
        }
      } finally {
        connection.release();
      }
    });

    // 立即返回视频ID
    res.json({
      success: true,
      data: {
        videoId,
        message: '视频生成已开始'
      }
    });

  } catch (error) {
    console.error('视频生成失败:', error);
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '视频生成失败'
    });
  }
};

// 获取视频生成进度
export const getVideoProgress = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const connection = await pool.getConnection();
    try {
      const [rows] = await connection.execute<VideoRow[]>(
        'SELECT * FROM videos WHERE video_id = ?',
        [id]
      );

      if (rows.length === 0) {
        return res.status(404).json({
          success: false,
          message: '视频不存在'
        });
      }

      const video = rows[0];
      res.json({
        success: true,
        data: {
          status: video.status,
          progress: video.status === 'completed' ? 100 : 
                   video.status === 'failed' ? 0 : 
                   video.status === 'processing' ? 50 : 0
        }
      });
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('获取视频进度失败:', error);
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '获取视频进度失败'
    });
  }
};

// 获取视频列表
export const getVideoList = async (req: Request, res: Response) => {
  try {
    const connection = await pool.getConnection();
    try {
      const [rows] = await connection.execute<VideoRow[]>(
        'SELECT * FROM videos ORDER BY created_at DESC'
      );
      
      // 处理视频数据，添加可访问的URL
      const videos = rows.map(video => ({
        id: video.video_id,
        status: video.status,
        createdAt: video.created_at,
        updatedAt: video.updated_at,
        url: video.status === 'completed' ? `/output/${path.basename(video.output_path)}` : undefined
      }));

      res.json({
        success: true,
        data: videos
      });
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('获取视频列表失败:', error);
    res.status(500).json({
      success: false,
      message: error instanceof Error ? error.message : '获取视频列表失败'
    });
  }
}; 